<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.0.js"></script>
<title>xml更新</title>
</head>

<body>

<?php
class UpdateCode
{
	var $version='V1.0';                      //设置最新版本号   
	var $xmlDir='loadxml';                    //设置安装目录
	var $logFile='update_log.txt';            //设置日志文件名
	var $files=array();                       //需要更新的文件数组
	var $file;                                //需要更新的文件
	var $string;                              //读取文件字符串
	var $result;                              //写入文件字符串	
	var $query;                               //查询代码
	var $code;                                //更新代码
	var $updateFile;                          //更新文件
	//var $updateFileInfo=array();            //项目信息	
	var $error;                               //错误信息
    var $xmlarr=array();                      //xml信息
	var $fqcarr=array();                      //查更信息
	var $uploadFile;                          //单个更新文件

	public function __construct($model=0,$uploadFile='')
	{
		if($model!=0)
		{
			$this->showInfo();
			if(!empty($uploadFile))
			{
				$this->uploadFile=$uploadFile;
			}
			$this->updateFile();
		}
		else{}
	}
	
    //提示信息
    function showInfo()
	{
		echo '<div style="color:">';
		echo '<p>';
		echo '<span>软件版本：'.$this->version.'</span><br/>';
		echo '<span>最近更新：'.file_get_contents($this->xmlDir.'/'.$this->logFile).'</span><br/>';
		echo '</p>';
		echo '</div>';
	}	
	
    //错误信息
	function getErrorInfo()
	{
		$errorInfo=array('code'=>$this->error,'msg'=>'','style'=>'');
		//更新代码错误
		if($this->error==101)
		{
			$errorInfo['style']='color:green';
			$errorInfo['msg']='更新成功';
		}
		if($this->error==102)
		{
			$errorInfo['style']='color:gray';
			$errorInfo['msg']='已更新';
		}
		if($this->error==103)
		{
			$errorInfo['style']='color:red';
			$errorInfo['msg']='更新失败';
		}
		//文件错误
		if($this->error==201)
		{
			$errorInfo['style']='color:red';
			$errorInfo['msg']='您没有设置更新目录 '.$this->xmlDir;
		}
		if($this->error==202)
		{
			$errorInfo['style']='color:red';
			$errorInfo['msg']='目录下没有更新文件';
		}
		if($this->error==203)
		{
			$errorInfo['style']='color:red';
			$errorInfo['msg']='目录下没有该更新文件';
		}		
        printf('<li>'.$this->file.'<span style="margin-left:50px;%s">%s<span></li>',$errorInfo['style'],$errorInfo['msg']);		
	}
	
	//转换php符号
	function pconv()
	{
		$this->string=str_replace(array('<?php','?>'),array('php_head','php_tail'),$this->string);
		return $this->string;
	}

	//转回php符号
	function bconv()
	{
		$this->string=str_replace(array('php_head','php_tail'),array('<?php','?>'),$this->string);
		return $this->string;
	}

	//读取文件内容	
	function getFileInfo()
	{
		$this->string=file_get_contents($this->file);
		return $this->string;
	}

	//ascii编码
	function chrConv($string)
	{
		$strlen=strlen($string);
		$convarr=array();
		$convstr='';
		for($i=0;$i<$strlen;$i++)
		{
			$ascii=ord(substr($string,$i,1));
			if($ascii>127)
			{
				$convarr[]=$ascii;
				$i+=2;
			}
			else
			{
				$convarr[]=$ascii;
			}
		}
		$convstr=implode(',',$convarr);
        //$this->chrConvBack($convstr);
		return $convstr;				
	}

	//ascii解码
	function chrConvBack($convstr)
	{
		$convarr=explode(',',$convstr);
		$string='';
		foreach($convarr as $key=>$val)
		{
			$string.=chr($val);
		}
		return $string;
	}	

    //检查状态
    function checkCodeState()
	{
		if(substr_count($this->string,$this->query)>0)
		{
			if(substr_count($this->string,$this->code)>0)
			{
				$this->error=102;
			}
			else
			{
				$this->error=101;
			}	
		}
		else
		{
			$this->error=103;
		}	
		/*方法二
		$string_0=$this->chrConv($this->query);
		$string_1=$this->chrConv($this->code);
		$string_2=$this->chrConv($this->string);
		if(strpos($string_2,$string_0))
		{
			if(strpos($string_2,$string_1))
			{
				$this->error=102;
			}
			else
			{
				$this->error=101;
			}	
		}
		else
		{
			$this->error=103;
		}
		*/		
	}	
	
    //读取更新文件
	function getUpdateFileInfo($updateFile)
	{
		$this->updateFile=$updateFile;
		$xml = simplexml_load_file($this->updateFile);
		//$xmlarr
		$i=0;
		$xmlarr=array();
		foreach($xml->children() as $child)
		{
			$xmlarr[$i][$child->getName()]=$child;
			$i++;
		}
		//$fqcarr
		$j=0;
		$this->fqcarr=array();
		foreach($xmlarr as $key=>$val)
		{
			if(isset($val['file']))
			{
				$this->fqcarr[$j]['file']=$xmlarr[$key]['file'];
				$this->fqcarr[$j]['query']=$xmlarr[$key+1]['query'];
				$this->fqcarr[$j]['code']=$xmlarr[$key+2]['code'];
				$j++;
			}
			else continue;
		}
        return $this->fqcarr;		
	}
	
	//执行文件更新
	function setUpdate()
	{		
		foreach($this->fqcarr as $fqc)
		{
			$this->file=$fqc['file'];
			$this->getFileInfo();
			$this->query=$fqc['query'];
			$this->code=$fqc['code'];
			$this->checkCodeState();
			if($this->error!=102)
			{
				$this->result=str_replace($this->query,$this->query.$this->code,$this->string);								
				file_put_contents($this->file,$this->result);
				//$this->rewrite();
			}
			$this->getErrorInfo();
		}
	}
	
    //重新写入
	function rewrite()
	{ 
		$filenum=fopen($this->file,"w"); 
		flock($filenum,LOCK_EX); 
		fwrite($filenum,$this->result); 
		fclose($filenum); 	
	}
	
	//更新文件
	function updateFile()
	{
		if($this->checkFile()!=false)		
		{
			foreach($this->files as $updateFile)
			{
				echo '<p style="color:white; background:blue; width:500px; text-align:center;">'.$updateFile.'</p>';
				$this->getUpdateFileInfo($this->xmlDir.'/'.$updateFile);
				$this->setUpdate();	
				//更新版本号（可把error提出来，如果出错则返回上个版本号）
				$myfile = fopen($this->xmlDir.'/'.$this->logFile, "w") or die("Unable to open file!");
				fwrite($myfile, $updateFile);
				fclose($myfile);
			}
		}
		
	}	
	
	//检查是否存在更新文件
	function checkFile()
	{
		//如果指定更新文件则更新指定文件，否则执行默认更新
		if(!empty($this->uploadFile))
		{
			if(file_exists($this->xmlDir.'/'.$this->uploadFile))
			{
				$this->files[]=$this->uploadFile;
				return true;
			}
			else
			{
				$this->error=203;
				$this->getErrorInfo();
				return false;				
			}
		}
		else
		{
			if(file_exists($this->xmlDir))
			{
				$dirs=scandir(__DIR__ . '/'.$this->xmlDir);
				foreach($dirs as $dir)
				{
					if(end(explode('.',$dir))=='xml')
					{
						//还要判断版本号是否正确
						if(intval($dir)>intval(file_get_contents($this->xmlDir.'/'.$this->logFile)))
						{
							$this->files[]=$dir;
						}						
					}
				}
				if(count($this->files)>0)
				{
					return true;
				}
				else
				{
					$this->error=202;
					$this->getErrorInfo();
					return false;
				}			
			}
			else
			{
				$this->error=201;
				$this->getErrorInfo();
				return false;
			}			
		}
	}
	
	//获取更新文件列表
	function getFilesList()
	{
		if(file_exists($this->xmlDir))
		{
			$dirs=scandir(__DIR__ . '/'.$this->xmlDir);
			foreach($dirs as $dir)
			{
				$arr = explode('.',$dir);
				if(end($arr)=='xml')
				{					
					$this->files[]=$dir;					
				}
			}
		}				
	}
	
}

function characet($data){
  if( !empty($data) ){    
    $fileType = mb_detect_encoding($data , array('UTF-8','GBK','LATIN1','BIG5')) ;   
    if( $fileType != 'UTF-8'){   
      $data = mb_convert_encoding($data ,'utf-8' , $fileType);   
    }   
  }   
  return $fileType;    
}

?>


<?php
$_REQUEST['act']=empty($_REQUEST['act'])? 'default':$_REQUEST['act'];

//初始页面
if($_REQUEST['act']=='default')
{
	$showPage="defaule";
	$deal=new UpdateCode();
	$deal->getFilesList();
}

//执行更新
elseif($_REQUEST['act']=='update')
{
	$showPage="update";
	
	$_REQUEST['model']=empty($_REQUEST['model'])? 0:$_REQUEST['model'];
	$_REQUEST['upFile']=empty($_REQUEST['upFile'])? 0:$_REQUEST['upFile'];
	
	if($_REQUEST['model']==1)
	{
		if(!empty($_REQUEST['upFile']))
		{
			$deal=new UpdateCode(1,$_REQUEST['upFile']);
		}
		else
		{
			echo '您没有选择更新文件';
		}
	}
	elseif($_REQUEST['model']==2)
	{
		$deal=new UpdateCode(2);
	}
	elseif($_REQUEST['model']==3)
	{
		$deal=new UpdateCode(3);
	}
	else
	{
		echo '请选择更新模式';
	}
}

//其他操作
else
{
	echo '无操作';
}
?>

<!--默认初始页面 default start-->
<?php if($showPage=="defaule"){ ?>
<div>
	<p>选择更新模式</p>
	<form name="form" action="update.php" method="get">
		<input type="radio" name="model" value="1"> 指定文件更新
		<select name="upFile" style="display:none">
		    <option value="0">选择更新文件</option>
		    <?php
				foreach($deal->files as $file)
				{
					echo '<option value="'.$file.'">'.$file.'</option>';
				}
			?>			
		</select>
		<input type="radio" name="model" value="2" checked="checked"> 默认顺序更新
		<input type="radio" name="model" value="3"> 默认全部更新
		<input type="hidden" name="act" value="update">
		<p><input type="button" value="执行更新" id="submitBtn"></p>
	</form>
</div>

<script>
$(document).ready(function(){
	//选择模式
	var model=$("input[name=model]");
	var modelx=$("input[name=model][value=1]");
	var upFile=$("select[name=upFile]");
	if(modelx.prop('checked')==true)
	{
		upFile.css({'display':''});
	}
	model.click(function(){
		if($(this).val()==1)
		{
			upFile.css({'display':''});
		}
		else
		{
			upFile.css({'display':'none'});
		}
	});
	//提交检查
	$("#submitBtn").click(function(){
		if(model.prop('checked')==true&&upFile.val()==0)
		{
			upFile.css({'border':'1px solid red'});
			alert('请选择更新文件')
		}
		else
		{
			$("form[name=form]").submit();
		}
	})
});
</script>
<?php } ?>
<!--默认初始页面 default end-->

</body>
</html>
